from rest_framework.exceptions import AuthenticationFailed
from rest_framework import status
from django_redis import get_redis_connection


class redis_connection():
    redis_connect = None
    
    def __init__(self, value="default"):
        self.redis_connect = get_redis_connection(value)

    def set_redis(self, key, value, timeout):
        self.redis_connect.set(key, value, timeout)

    def get_redis(self, key):
        data = self.redis_connect.get(key)
        if data is None:
            return False
            # raise AuthenticationFailed('无效的token.')
            # raise AuthenticationFailed({"status": status.HTTP_401_UNAUTHORIZED,"code": "40002", "message": "无效的token"})
        
        return data.decode('utf-8')
    
    def exists(self, key):
        return self.redis_connect.exists(key)

    def flushAll(self):
        return self.redis_connect.flushall()